<script setup lang="ts">
import { computed, reactive, watch } from 'vue'
import { useNaiveForm, useFormRules } from '@/hooks/common/form'
import { createDefaultModel, inventoryDisplayGroup, listingGroup } from '../_list/config'
import { editGoods, addGoods } from '@/service/api/product'
import { useMessage } from 'naive-ui'

const message = useMessage()

interface Props {
  operateType: NaiveUI.TableOperateType
  rowData: Api.Product.GoodsListItem | null
  categoryOptions: {
    label: string
    value: number
  }[]
}

interface Emits {
  (e: 'submitted'): void
}

const { rowData, categoryOptions, operateType } = defineProps<Props>()

const emit = defineEmits<Emits>()

const visible = defineModel<boolean>('visible', {
  default: false,
})

const { formRef, validate, restoreValidation } = useNaiveForm()

const { defaultRequiredRule } = useFormRules()

const rules = {
  title: defaultRequiredRule,
  status: defaultRequiredRule,
}

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: '新增',
    edit: '修改',
  }
  return titles[operateType]
})

const model = reactive(createDefaultModel())

const handleInitModel = () => {
  Object.assign(model, createDefaultModel())

  if (operateType === 'edit' && rowData) {
    Object.keys(model).forEach((key) => {
      model[key] = rowData[key]
    })
  }
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel()
    restoreValidation()
  }
})

const handleSubmit = async () => {
  await validate()

  const apiCall = operateType === 'add' ? addGoods : editGoods
  const { data } = await apiCall(model)

  if (data) {
    emit('submitted')
    message.success('操作成功')
  } else {
    message.error('操作失败')
  }
}
</script>

<template>
  <NDrawer v-model:show="visible" :width="500">
    <NDrawerContent :title="title" closable>
      <NForm ref="formRef" :model :rules>
        <NFormItem label="商品名称" path="title">
          <NInput v-model:value="model.title" placeholder="波斯猫" />
        </NFormItem>

        <NFormItem label="商品分类" path="category_id">
          <NSelect v-model:value="model.category_id" placeholder="请选择" :options="categoryOptions" />
        </NFormItem>
        <NFormItem label="商品描述" path="desc">
          <NInput v-model:value="model.desc" placeholder="商品描述默认值" type="textarea" :autosize="{
              minRows: 3,
              maxRows: 5,
            }" />
        </NFormItem>
        <NFormItem label="单位" path="unit">
          <NInput v-model:value="model.unit" style="width: 300px" :placeholder="model.unit" />
        </NFormItem>
        <NFormItem label="总库存" path="stock">
          <NInputNumber v-model:value="model.stock" placeholder="100" style="width: 200px">
            <template #suffix>{{ model.unit }}</template>
          </NInputNumber>
        </NFormItem>
        <NFormItem label="库存预警" path="min_stock">
          <NInputNumber v-model:value="model.min_stock" placeholder="10" style="width: 200px">
            <template #suffix>{{ model.unit }}</template>
          </NInputNumber>
        </NFormItem>
        <NFormItem label="最低销售价" path="min_oprice">
          <NInput v-model:value="model.min_price" placeholder="100" style="width: 200px">
            <template #suffix>元</template>
          </NInput>
        </NFormItem>
        <NFormItem label="最低原价" path="min_price">
          <NInput v-model:value="model.min_oprice" placeholder="100" style="width: 200px">
            <template #suffix>元</template>
          </NInput>
        </NFormItem>
        <NFormItem label="库存显示" path="inputValue">
          <n-radio-group v-model:value="model.stock_display" name="radiogroup" :default-value="model.stock_display">
            <n-space>
              <n-radio v-for="song in listingGroup" :key="song.value" :value="song.value">
                {{ song.label }}
              </n-radio>
            </n-space>
          </n-radio-group>
        </NFormItem>
        <NFormItem label="是否上架" path="inputValue">
          <n-radio-group v-model:value="model.status" name="radiogroup" :default-value="model.status">
            <n-space>
              <n-radio v-for="song in inventoryDisplayGroup" :key="song.value" :value="song.value">
                {{ song.label }}
              </n-radio>
            </n-space>
          </n-radio-group>
        </NFormItem>
      </NForm>
      <NButton type="primary" class="ml-2 mr-3" @click="handleSubmit">提交</NButton>
      <NButton @click="visible = false">取消</NButton>
    </NDrawerContent>
  </NDrawer>
</template>
